package com.wxw.jwt.controller;


import com.wxw.jwt.po.JwtToken;
import com.wxw.jwt.po.SysUser;
import com.wxw.jwt.uitls.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cnm
 * @since 2021-08-30
 */
@RestController
@RequestMapping("/auth")
@Slf4j
@Api(tags = "用户登陆接口")
public class SysUserController {

    @PostMapping("login")
    public String login(@RequestBody SysUser sysUser) {
        // 非空判断
        if (sysUser == null) {
            return null;
        }
        if (sysUser.getUsername() == null || sysUser.getPassword() == null) {
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                sysUser.getUsername(),
                sysUser.getPassword()
        );
        try {
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            throw new AuthenticationException("登录失败");
        }
        return "登录成功";

    }
    @ApiOperation("用户登陆接口")
    @PostMapping("loginJwt")
    public String loginJwt(@RequestBody SysUser sysUser) {

        /**
         * 在此做登陆校验就可
         */
        try {
            //144000毫秒=24分钟
            String token = JwtUtil.createToken(sysUser.getUsername(), 1440000L);
            Subject subject = SecurityUtils.getSubject();
            JwtToken jwtToken = new JwtToken(token);
            subject.login(jwtToken);
            return token;
        } catch (AuthenticationException e) {
            log.error("登录失败");
            throw new AuthenticationException("登录失败");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "登录失败";


    }
    @ApiOperation("获取token信息")
    @GetMapping("getInfo")
    public String getInfo() {
        return SecurityUtils.getSubject().getPrincipal().toString();
    }
    @ApiOperation("测试token实体类")
    @GetMapping("getTokenPo")
    public JwtToken getTokenPo() {
        JwtToken token = new JwtToken("token");
        token.setToken("123");
        return token;
    }
    @RequestMapping("error")
    public String error() {
        return "fail";
    }


}

